<%@ page language="java" import="com.alibaba.fastjson.JSONObject" pageEncoding="UTF-8" %>
<%@ page import="com.engine.encrypt.biz.DecryptResourceComInfo" %>
<%@ page import="okhttp3.*" %>
<%@ page import="weaver.common.DateUtil" %>
<%@ page import="weaver.conn.RecordSet" %>
<%@ page import="weaver.general.BaseBean" %>
<%@ page import="weaver.general.Util" %>
<%@ page import="java.math.BigInteger" %>
<%@ page import="java.nio.charset.StandardCharsets" %>
<%@ page import="java.security.MessageDigest" %>
<%@ page import="java.util.Base64" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.Random" %>
<%@ page import="java.util.concurrent.TimeUnit" %>
<%--发送移动短信验证码--%>
<%
    BaseBean baseBean = new BaseBean();
    String loginid = Util.null2String(request.getParameter("loginid"));
    String yzm = generateRandomNum();
    RecordSet rs = new RecordSet();
    Map<String, Object> apidatas = new HashMap<String, Object>();
    boolean status = false;
    try {
        rs.executeQuery("select id,mobile from hrmresource where loginid=?", loginid);
        if (rs.next()) {
            String id = Util.null2String(rs.getString("id"));
            String mobile = Util.null2String(rs.getString("mobile"));
            if (mobile.length() > 11) {
                DecryptResourceComInfo decryptResourceComInfo = new DecryptResourceComInfo();
                mobile = decryptResourceComInfo.getMobile(id);
            }

            baseBean.writeLog(">>>>>sendSmsByLoginid>>>>>mobile=" + mobile + ",yzm=" + yzm);
            String url = "http://112.35.10.201:5992/sms/norsubmit";
            String ecName = "中环领先半导体材料有限公司";
            String apId = "zhlx1";
            String secretKey = "a123456";
            String content = "验证码：" + yzm + "，您正在进行验证操作（10分钟内有效），如非本人操作请忽略本短信";
            String sign = "E4HfiwovF";
            String addSerial = "";
            String mac = stringToMD5(ecName + apId + secretKey + mobile + content + sign + addSerial);
            JSONObject paramsJson = new JSONObject(true);
            paramsJson.put("ecName", ecName);
            paramsJson.put("apId", apId);
            paramsJson.put("mobiles", mobile);
            paramsJson.put("content", content);
            paramsJson.put("sign", sign);
            paramsJson.put("addSerial", addSerial);
            paramsJson.put("mac", mac);
            String params = paramsJson.toJSONString();
            baseBean.writeLog(">>>>>sendSmsByLoginid>>>>>params=" + params);
            String paramsEncode = Base64.getEncoder().encodeToString(params.getBytes(StandardCharsets.UTF_8));
            baseBean.writeLog(">>>>>sendSmsByLoginid>>>>>paramsEncode=" + paramsEncode);
            JSONObject resultJson = sendOKHttpRequest(url, paramsEncode);
            baseBean.writeLog(">>>>>sendSmsByLoginid>>>>>resultJson=" + resultJson);
            String code = Util.null2String(resultJson.getString("code"));
            if ("success".equals(code)) {
                String dataStr = Util.null2String(resultJson.getString("data"));
                JSONObject dataJson = JSONObject.parseObject(dataStr);
                if ("success".equals(dataJson.getString("rspcod"))) {
                    String fullDate = DateUtil.getFullDate();
                    String sql = "update cus_fielddata set field129=?,field127=? where scopeid='-1' and scope='HrmCustomFieldByInfoType' and id=?";
                    status = rs.executeUpdate(sql, fullDate,yzm, id);
                }
            }
        }
    } catch (Exception e) {
        baseBean.writeLog(">>>>>sendSmsByLoginid>>>>>Exception=" + e);
    }
    apidatas.put("status", status);
    out.print(JSONObject.toJSONString(apidatas));
%>
<%!
    /**
     * MD5
     * @param plainText
     * @return
     */
    private static String stringToMD5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(plainText.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            throw new RuntimeException("没有这个md5算法！");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }

    /**
     * 生成验证码
     * @return
     */
    private static String generateRandomNum() {
        int[] a = new int[6];
        Random r = new Random();
        a[0] = r.nextInt(6);
        for (int i = 1; i < 6; i++) {
            //数组存入6个数
            a[i] = r.nextInt(10);
            for (int j = 0; j < i; j++) {
                if (a[j] == a[i]) {
                    i--;
                    break;
                }
            }
        }
        // 遍历
        StringBuffer str = new StringBuffer();
        for (int s : a) {
            str.append(s);
        }
        return str.toString();
    }

    /**
     * HttpRequest
     * @param apiUrl
     * @param params
     * @return
     */
    private static JSONObject sendOKHttpRequest(String apiUrl, String params) {
        JSONObject resultJson = new JSONObject();
        String code = "failure";
        String message = "";
        String data = "";
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, params);
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            if (!"".equals(result)) {
                data = result;
                code = "success";
            } else {
                message = "response result is null";
            }
        } catch (Exception e) {
            message = "response timeout";
            e.printStackTrace();
        }
        resultJson.put("code", code);
        resultJson.put("data", data);
        resultJson.put("message", message);
        return resultJson;
    }

%>



